package org.beynet.docs.http;

import org.apache.log4j.Logger;

public class BandwithSaver {
    
    private BandwithSaver(Integer maxPerSec) {
        logger.info("Creating bandwidth saver with max bytes per sec equal to "+maxPerSec);
        this.maxPerSec         = maxPerSec ;
        this.lastTime          = 0 ;
        this.currentSecondSent = Integer.valueOf(0) ;
        this.lastSecond        = maxPerSec ;
    }
    
    public static synchronized BandwithSaver getInstance(Integer maxPerSec) {
        if (_instance == null) {
            _instance = new BandwithSaver(maxPerSec);
        }
        return(_instance);
    }
    
    /**
     * add content sent and time used to send this content
     * @param sent
     * @param duration
     */
    public synchronized void addContentSent(int sent) {
        if (this.maxPerSec.intValue()==0) return;
        long d = System.currentTimeMillis();
        if (d-lastTime>1000) {
            this.lastSecond = this.currentSecondSent;
            this.currentSecondSent = Integer.valueOf(sent);
            lastTime = d ;
        }
        else this.currentSecondSent=Integer.valueOf(this.currentSecondSent.intValue()+sent);
    }
    
    public synchronized void couldSend() {
        if (this.maxPerSec.intValue()==0) return;
        if (lastSecond.intValue()>maxPerSec.intValue()) {
            double res = (1.0*lastSecond.intValue())/maxPerSec.intValue() ;
            if (res>1) {
                long toSleep = (long)((res-1)*1000);
                try {
                    wait(toSleep);
                } catch (InterruptedException e) {
                    
                }
            }
        }
    }
    
    public Integer maxPerSec         ; 
    public long lastTime             ; 
    public Integer currentSecondSent ;
    public Integer lastSecond        ; 
    
    private static BandwithSaver _instance = null ;
    private final static Logger logger = Logger.getLogger(BandwithSaver.class);
    
}
